package org.one.stone.soup.grfxML.plugin.function;


import org.one.stone.soup.grfxML.GrfxMLEngine;
import org.one.stone.soup.grfxML.IPrimative;
import org.one.stone.soup.grfxML.plugin.SimplePlugin;
import org.one.stone.soup.grfxML.plugin.grfxMLCaster;
import org.one.stone.soup.mjdb.data.field.DataLinker;
import org.one.stone.soup.mjdb.data.field.Field;
import org.one.stone.soup.mjdb.data.field.LockException;

public class RouteMapping extends SimplePlugin {


	public static final int ARG_MAP = 0;

	org.one.stone.soup.grfxML.DataText map = new org.one.stone.soup.grfxML.DataText();

	Field[] source;
	String[] sourceAttribute;
	Field[] target;
	String[] targetAttribute;
/**
 * RouteMapping constructor comment.
 */
public RouteMapping (GrfxMLEngine engine){
	super(engine);
}
/**
 * initialize method comment.
 */
public void initialize()
{
	int size = map.size();

	String sourceName;
	String targetName;

	source = new Field[size];
	sourceAttribute = new String[size];
	target = new Field[size];
	targetAttribute = new String[size];

	Field found;

	for(int loop=0;loop<size;loop++)
	{
		String data = map.get(loop).getValue();

		String argA = null;
		String argB = null;

		if(data.indexOf("=")>0)
		{
			argB = data.substring(0,data.indexOf("="));
			argA = data.substring(data.indexOf("=")+1);

			if(
				argA.indexOf(".")<0 ||
				argB.indexOf(".")<0
			)
				continue;

			sourceName = getPath()+argA.substring( 0,argA.indexOf(".") );
			sourceAttribute[loop] = argA.substring( argA.indexOf(".")+1 );

			targetName = getPath()+argB.substring( 0,argB.indexOf(".") );
			targetAttribute[loop] = argB.substring( argB.indexOf(".")+1 );

			found = getEngine().getAPI().getField(sourceName);
			if(found instanceof IPrimative)
			{
				source[loop] = (Field)found;
				sourceAttribute[loop] = ((IPrimative)source[loop]).getModifier().getAttributeName( sourceAttribute[loop] );
			}

			found = getEngine().getAPI().getField(targetName);
			if(found instanceof IPrimative)
			{
				target[loop] = (Field)found;
				targetAttribute[loop] = ((IPrimative)target[loop]).getModifier().getAttributeName( targetAttribute[loop] );
			}
		}
	}
}
/**
 * process method comment.
 */
public void process()
{
	for(int loop=0;loop<source.length;loop++)
	{
		if( source[loop]==null )
			continue;

		if( !source[loop].hasChanged() )
			continue;

		String value = source[loop].getValue( sourceAttribute[loop] );

		try{
			((IPrimative)target[loop]).setValue( targetAttribute[loop],value,this );
		} catch(LockException le){}
	}
}
/**
 * register method comment.
 */
public void register(DataLinker store)
{

	map = grfxMLCaster.cast(map,getArg(map,ARG_MAP,store));

}
/**
 * replace method comment.
 */
public void replace(Field oldObj, Field newObj)
{

	map = grfxMLCaster.replace(map,oldObj,newObj);

}
/**
 * stop method comment.
 */
public void stop() {}
}
